<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" :leftIconColor="'#fff'" :titleColor="'#fff'" :textAlign="'center'"
        title="个人主页" />
      <!-- 运动员切换条 -->
      <view class="athlete-switch-bar">
        <view class="left">
          <text class="label">当前运动员：</text>
          <text class="name">{{ currentPlayer ? currentPlayer.username : '未选择' }}</text>
        </view>
        <view class="switch" @click="switchAthlete">
          <text>切换</text>
          <view class="icon-box">
            <image :src="imgUrl + 'switch@2x.png'" class="icon" mode="aspectFit" />
          </view>
        </view>
      </view>
      <!-- 顶部背景 -->
      <view class="profile-header">
        <image class="logo" :src="imgUrl + 'WechatIMG8@2x.png'" />
        <text class="join-days">已加入草源{{ joinDays }}天</text>
      </view>
      <!-- 个人信息 -->
      <view class="profile-info">
        <image class="avatar" :src="userInfoProps.avatar?userInfoProps.avatar:imgUrl + 'avatar1@2x.png'" />
        <view class="user-info">
          <view class="user-name">{{ userInfoProps.username }}</view>
          <view class="user-meta">
            <text>性别：{{ userInfoProps.gender == 0 ? '男' : userInfoProps.gender == 1 ? '女' : '未知' }}</text>
            <!-- <text class="meta-divider">|</text>
            <text>城市：{{ user.city }}</text> -->
          </view>
          <view class="user-meta">
            <!-- <text>性别：{{ user.gender }}</text> -->
            <!-- <text class="meta-divider">|</text> -->
            <text>城市：{{ userInfoProps.city }}</text>
          </view>
          <view class="user-stats">
            <view class="stat">
              <image :src="imgUrl + 'heart@2x.png'" class="icon-btn mr-5" />
              {{ userInfoProps.like_num }}
            </view>
            <text class="stat-divider">|</text>
            <view class="stat">
              <view class="iconfont">
                <image class="icon-btn mr-5 ml-15" :src="imgUrl + 'userPlus@2x.png'" />
              </view>
              {{ userInfoProps.follow_num }}
            </view>
          </view>
        </view>
        <view class="profile-actions">
          <button class="share-btn" @click="onShare">
            <image :src="imgUrl + 'share.png'" class="icon-btn" />
            <text class="share-text">转发</text>
          </button>
          <button class="unfollow-btn" @click="onUnfollow">取关</button>
        </view>
      </view>

      <!-- 最佳成绩 -->
      <view class="section">
        <view class="section-header">
          <text>最佳成绩</text>
          <!-- <image class="logo" :src="imgUrl + 'WechatIMG8@2x.png'" /> -->
        </view>
        <view class="section-content">
          <view v-if="bestRecords.length === 0" class="no-records">
            暂无最佳成绩
          </view>
          <view v-else class="records-list">
            <view v-for="(record, index) in bestRecords" :key="index" class="record-item">
              <view class="event-type">{{ record.item_name }}</view>
              <view class="pb-time">
                <text class="pb-label">{{record.tag}} </text>
                <text class="pb-value">{{ record.score }}</text>
              </view>
              <view class="record-info">
                <view class="location">{{ record.city }}</view>
                <view class="date">{{ record.end_time }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 获得荣誉 -->
      <view class="section">
        <view class="section-header">
          <text>获得荣誉</text>
          <!-- <image class="logo" :src="imgUrl + 'WechatIMG8@2x.png'" /> -->
        </view>
        <view class="section-content">
          <view v-if="honorList.length === 0" class="no-honors">
            暂无获得荣誉
          </view>
          <view v-else class="honors-list">
            <view v-for="(honor, index) in honorList" :key="index" class="honor-item">
              <view class="champion-tag">{{ honor.rank ? (honor.rank == 1 ? '冠军' : honor.rank == 2 ? '亚军' : honor.rank
                == 3 ? '季军' : '第' + honor.rank + '名') : '' }}</view>
              <view class="honor-content">
                <view class="top-row">
                  <view class="event-type">{{ honor.item_name }}</view>
                  <view class="group">{{ honor.group_name }}</view>
                  <view class="location">{{ honor.city }}</view>
                </view>
                <view class="bottom-row">
                  <view class="venue">{{ honor.event_address }}</view>
                  <view class="date">{{ honor.end_time }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 开关 -->
      <view class="switch-row">
        <view class="switch-label">最佳成绩公开</view>
        <uv-switch v-model="publicBest" activeColor="#213165" inactiveColor="#fff" />
        <view class="switch-label">获得荣誉公开</view>
        <uv-switch v-model="publicHonor" activeColor="#213165" inactiveColor="#fff" />
      </view>
    </view>
    <!-- 运动员选择弹窗 -->
    <uni-popup ref="athletePopup" type="bottom" :safe-area="true">
      <view class="athlete-popup">
        <view class="popup-header">
          <text class="popup-title">选择运动员</text>
          <view class="close-btn" @click="closeAthletePopup">
            <text class="close-text">×</text>
          </view>
        </view>
        <scroll-view scroll-y class="popup-scroll">
          <view v-if="playerList.length === 0" class="empty-state">暂无运动员信息</view>
          <view v-else>
            <view v-for="player in playerList" :key="player.id" class="player-item"
              :class="{selected: currentPlayer && currentPlayer.id===player.id}" @click="selectPlayer(player)">
              <image :src="player.avatar || (imgUrl + 'avatar1@2x.png')" class="player-avatar" mode="aspectFill" />
              <view class="player-info">
                <text class="player-name">{{ player.username }}</text>
                <text class="player-mobile">手机号：{{ player.mobile || 'N/A' }}</text>
              </view>
              <text v-if="currentPlayer && currentPlayer.id===player.id" class="status-selected">已选择</text>
              <text v-else class="status">选择</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </scroll-view>


</template>

<script setup>
  import { ref, computed } from 'vue'
  import { useOutsideAppStore } from '@/store/app'
  import { imgUrl } from '@/utils/config'
  import { onShow, onLoad } from '@dcloudio/uni-app';
  import { useRequest } from '@/api';
  import XlmTopNav from '@/components/XlmTopNav/index.vue';
  import { ShareUtils, ShareConfigGenerator } from '@/utils/shareUtils.js'
  const { API_MEMBER_PERSONSCORE_POST, API_MEMBER_LISTATHLETE_POST } = useRequest()
  const appStore = useOutsideAppStore()
  const navHeight = computed(() => appStore.navHeight)
  const scrollTop = ref(0)
  const onPageScroll = (e) => {
    scrollTop.value = e.detail.scrollTop
  }
  const athlete_id = ref('');
  const athlete_name = ref('');
  const joinDays = 110
  const user = ref({
    avatar: '',
    name: '',
    gender: '',
    city: '',
    likes: 0,
    fans: 0
  })
  const userInfoProps = ref({
    avatar: '',
    name: '',
    gender: '',
    city: '',
    likes: 0,
    fans: 0
  })
  const publicBest = ref(false)
  const publicHonor = ref(true)

  // 最佳成绩数据
  const bestRecords = ref([
    // {
    //   item_name: '50M蝶泳',
    //   tag:'',
    //   score: '26:00',
    //   city: '深圳站',
    //   end_time: '2025.12.12'
    // },
    // {
    //   item_name: '50M自由泳',
    //   tag:'',
    //   score: '26:00',
    //   city: '深圳站',
    //   end_time: '2025.12.12'
    // }
  ])

  // 荣誉数据
  const honorList = ref([
    // {
    //   rank: '冠军',
    //   item_name: '50M蝶泳',
    //   group_name: '公开男子组',
    //   city: '深圳站',
    //   enevt_province: '广东省',
    //   enevt_city: '深圳市',
    //   enevt_region: '深圳大学(南区)体育中心–游泳馆',
    //   event_address: '深圳市南山区',
    //   end_time: '2025.12.12'
    // },
    // {
    //   rank: '亚军',
    //   item_name: '50M自由泳',
    //   group_name: '公开男子组',
    //   city: '深圳站',
    //   enevt_province: '广东省',
    //   enevt_city: '深圳市',
    //   enevt_region: '深圳大学(南区)体育中心–游泳馆',
    //   event_address: '深圳市南山区',
    //   end_time: '2025.12.12'
    // }
  ])

  // 运动员切换
  const athletePopup = ref(null)
  const playerList = ref([])
  const currentPlayer = ref(null)

  const switchAthlete = () => {
    if (playerList.value.length === 0) {
      uni.showToast({ title: '暂无运动员信息', icon: 'none' })
      return
    }
    athletePopup.value && athletePopup.value.open()
  }
  const closeAthletePopup = () => {
    athletePopup.value && athletePopup.value.close()
  }
  const selectPlayer = (player) => {
    currentPlayer.value = player
    closeAthletePopup()
    uni.showToast({ title: `已选择：${player.username}`, icon: 'success' })
    // 切换后刷新数据
    getPersonScore(player.id)
  }

  const onShare = () => {
    // 使用分享工具类
    const shareConfig = ShareConfigGenerator.generatePersonalHomepageShareConfig(
      user.value.name,
      user.value.avatar,
      user.value.likes,
      user.value.fans
    )
    ShareUtils.share(shareConfig)
  }

  // 微信小程序分享配置
  // 分享给好友
  const onShareAppMessage = () => {
    const shareData = {
      title: `${user.value.name}的个人主页`,
      desc: `获赞${user.value.likes}，粉丝${user.value.fans}，快来关注吧！`,
      path: `/pages/personalHomepage/index?userId=${user.value.name}`,
      imageUrl: user.value.avatar || ''
    }

    ShareUtils.recordShareEvent('share_to_friend', shareData)
    return shareData
  }

  // 分享到朋友圈
  const onShareTimeline = () => {
    const shareData = {
      title: `${user.value.name}的个人主页`,
      query: `userId=${user.value.name}`,
      imageUrl: user.value.avatar || ''
    }

    ShareUtils.recordShareEvent('share_to_timeline', shareData)
    return shareData
  }
  const onUnfollow = () => {
    uni.showToast({ title: '已取关', icon: 'none' })
  }
  const getPersonScore = async (athleteId) => {
    if (!athleteId) return
    let params = {
      page: 1,
      page_size: 10,
      athleteid: athleteId
    }
    userInfoProps.value = {
      avatar: '',
      username: '',
      gender: '',
      city: '',
      likes: 0,
      fans: 0
    }
    bestRecords.value = []
    honorList.value = []
    try {

      const res = await API_MEMBER_PERSONSCORE_POST(params)
      console.log('getPersonScore', res)

      if (res.code === 1) {
        userInfoProps.value = res.data;
        bestRecords.value = res.data.nicescore ? res.data.nicescore : [];
        honorList.value = res.data.nicehonor ? res.data.nicehonor : [];
        if (res.data.isshow_score == 1) {
          publicBest.value = true
        } else {
          publicBest.value = false
        }
        if (res.data.isshow_honor == 1) {
          publicHonor.value = true
        } else {
          publicHonor.value = false
        }
        const data = Array.isArray(res.data?.data) ? res.data.data[0] : res.data
        if (data) {
          user.value = {
            avatar: data.avatar || user.value.avatar || imgUrl + 'avatar1@2x.png',
            name: data.username || data.name || user.value.name || '未填写',
            gender: data.gender || user.value.gender || '未知',
            city: data.city || user.value.city || '',
            likes: data.likes || 0,
            fans: data.fans || 0
          }
        }
      } else {
        uni.showToast({ title: res.msg, icon: 'none' })
      }
      console.log('user', user.value);

    } catch (error) {
      uni.showToast({ title: error.message, icon: 'none' })
    }
  }
  onShow(() => {
    const pages = getCurrentPages(); // 获取当前页面栈
    const currentPage = pages[pages.length - 1]; // 获取当前页面
    console.log('currentPage', currentPage);

    const options = currentPage.options; // 获取当前页面的参数
    const { athlete_id: paramAthleteId, athlete_name: paramAthleteName } = options;
    athlete_id.value = paramAthleteId || '';
    athlete_name.value = paramAthleteName || '';
    console.log('athlete_id', athlete_id.value);
    console.log('athlete_name', athlete_name.value);

    if (athlete_id.value) {
      getPersonScore(athlete_id.value)
    } else {
      getPlayerList()
    }

  })

  const getPlayerList = async () => {
    let params = { page: 1, page_size: 20 }
    playerList.value = []
    try {
      const res = await API_MEMBER_LISTATHLETE_POST(params)
      if (res.code === 1) {
        playerList.value = res.data?.data || []
        if (!currentPlayer.value && playerList.value.length > 0) {
          currentPlayer.value = playerList.value[0]
          // 默认回显当前运动员的数据
          getPersonScore(currentPlayer.value.id)
        }
      } else {
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    } catch (error) {
      uni.showToast({ title: error.message, icon: 'none' })
    }
  }
</script>

<style lang="scss" scoped>
  @import './index.scss';
</style>
<style>
  .aaa .custom-nav-content .custom-nav .left-icon {
    color: #fff !important;
    font-weight: normal;
  }

  .aaa .custom-nav-content .custom-nav .title {
    color: #fff !important;
    font-weight: normal;
  }

  /* 修改关闭状态下的圆点背景色 */
  .switch-row .uv-switch__node {
    background-color: #213165 !important;
  }

  /* 修改打开状态下的圆点背景色 */
  .switch-row .uv-switch__node--on {
    background-color: #fff !important;
  }
</style>